package com.yanqu.road.server.cmd.union.cross;

import com.yanqu.road.entity.player.CrossUserBaseInfo;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.union.UnionMember;
import com.yanqu.road.entity.union.cross.CrossUnionInfo;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.pb.CrossUnionPb;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.pb.union.UnionProto;
import com.yanqu.road.server.cmd.CrossCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.union.CrossUnionJoinApplyMgr;
import com.yanqu.road.server.manager.union.CrossUnionMgr;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.string.StringUtils;

@Cmd(code = Protocol.C_UNION_JOIN, desc = "请求加入联盟")
public class CrossJoinUnionCmd extends CrossCommand {


    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        return true;
    }

    @Override
    public void execute(YanQuMessage packet) throws Exception {


        UnionProto.UnionJoinGameToCrossMsg reqMsg = UnionProto.UnionJoinGameToCrossMsg.parseFrom(packet.getBytes());
        String unionUid = reqMsg.getUnionUid();

        //重新加入联盟，需要判断时间
        long nowTime = System.currentTimeMillis() / 1000;
        UnionMember member = CrossUnionMgr.getUnionMember("", packet.getPlayerId());
        if(null != member && nowTime - member.getQuitTime() < GameConfig.UNION_NEXT_JOIN_NEED_TIME){
            ret = GameErrorCode.E_UNION_NEXT_JOIN_TIME_NO_ENOUGH;

        }else {
            UserBaseInfo userBaseInfo = PlayerBasePb.parseToUserBaseInfo(reqMsg.getPlayerBaseData());
            CrossUserMgr.updateUserBaseInfo(packet.getPlayerId(), userBaseInfo);

            CrossUserBaseInfo baseInfo = CrossUserMgr.getCrossUserBaseInfo(packet.getPlayerId());
            if (!StringUtils.isNullOrEmpty(unionUid)) {
                ret = CrossUnionJoinApplyMgr.addUnionJoinApply(baseInfo, unionUid);
            } else {
                ret = CrossUnionMgr.randomJoin(baseInfo, reqMsg.getExcludeUnionListList());
            }
        }


        UnionProto.UnionJoinRespMsg.Builder respMsg = UnionProto.UnionJoinRespMsg.newBuilder();
        respMsg.setRet(ret);
        CrossUnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionUid);
        if(unionInfo != null){
            respMsg.setUnion(CrossUnionPb.parseUnionTempMsg(unionInfo));
        }
        MessageHelper.sendPacket(serverId, packet.getPlayerId(), YanQuMessageUtils.buildMessage(Protocol.U_UNION_JOIN, respMsg));

    }

    @Override
    public void sendData() {

    }
}
